package com.vietnam.power.job;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.vietnam.power.domain.FileUpload;
import com.vietnam.power.service.FileService;
import com.vietnam.power.service.MessageService;

public class MainJobs extends QuartzJobBean {
	private static Logger logger = Logger.getLogger(MainJobs.class);
	@Autowired
	private MessageService messageService;

	@Autowired
	private FileService fileService;
	
	@Override
	protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
		logger.debug("Execute job");
		try {
			messageService.sendEmail();
			messageService.fetchEmail();
			this.deleteUnusedFiles();
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	private void deleteUnusedFiles() throws IOException {
		List<FileUpload> fileUploads = fileService.getUnusedFiles();
		Properties properties = new Properties();
		/*to access your filename.properties file */
		properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("/systemconfig/system.properties"));
		
		String  appPath = properties.getProperty("server.upload.file.path");
		
		for (FileUpload fileUpload : fileUploads) {
			fileService.deleteFile(fileUpload.getId(), appPath);
		}
	}

}
